//SA mpi
//$Id: sa_mpi.h 612 2010-11-28 18:40:53Z Oleg.Bulychov $
#pragma once

#include "src/heo/include/lf_endl.h"
#include "src/heo/include/easy_mpi.h"
#include "src/heo/include/ring_coop.h"
#include "sa_common.h"
//__________________________________________________________________________________
/**
The Multistart Model with Ring Cooperation
*/
template<class T>
class SA_MPI:
    public SA<T>
{
public:
    typedef typename SA<T>::TEnvironment TEnvironment;
    typedef typename SA<T>::TSolution TSolution;

    typedef typename SA<T>::TDirection TDirection;
    typedef typename SA<T>::TCostType  TCostType;

protected:
    ring_cooperation<mpi::recv, mpi::send, mpi::isend> coop_;
public:
    template<class V>
    void accept(V& v)
    {
        v(static_cast<SA<T>&>(*this), "/");
        v(VAR_(coop));
    }

    void solve(Solution_Pool<typename TEnvironment::TSolution>& pool,
        typename TEnvironment::TStatistics& stat, mpi::communicator& comm)
    {
        ASSERT_(this->rank_ == comm.rank());
        int np   = comm.size();
        int prev = (np + this->rank_ - 1) % np;
        int next = (this->rank_ + 1)      % np;

        this->init_From_Pool(pool);
        if (this->coop_.is_Async_Mode())
            this->init_Async_Buffer();
        this->set_Initial_Temperature();
        this->calc_Max_Step();
        this->show_Progress(0);
        stat.update(0, 0, *this, this->env_);

        for (int step = 1; step <= this->max_step_; ++step)
        {
            if (coop_.cooperate(*this, this->rank_, prev, next, np, step,
                comm))
            {
                if (this->coop_.is_Async_Mode())
                {
                    if (this->sent_stop_)
                        break;
                }
                else
                {
                    int stop = 0;
                    comm.all_reduce(this->pending_stop_, stop, MPI_SUM);
                    if (stop)
                    {
                        if (this->rank_ < this->env_->debug_level_)
                        {
                            std::cout << std::setw(2) << this->rank_ << ":" << std::setw(5) << step
                                << ": stop reduced" << lf;
                        }
                        break;
                    }
                }
            }
            else
            {
                this->move();
            }

            if (this->is_Acceptable_Solution())
            {
                this->accept_Solution();
                this->show_Progress(step);
                if (this->keep_best_)
                {
                    this->update_Best_Solution();
                }
            }

            if (this->stop(step))
            {
                if (1 == np || !this->coop_.get_Rate())
                    break;//:no coop - no need for 'pending stop'
                this->pending_stop_ = 1;
            }

            this->update_Temperature(step);
            stat.update(step, 0, *this, this->env_);
        }

        this->clear_MPI(prev, comm);

        update_Pool(pool, comm, np);
    }
private:
    void update_Pool(Solution_Pool<typename TEnvironment::TSolution>& pool,
        mpi::communicator& comm, int np)
    {
        TSolution& final_sol = this->get_Final_Solution();
        if (0 == this->rank_)
        {
            pool.sol_list_.resize(np);
            pool.sol_list_[0].init(this->env_, this->rnd_);
            pool.sol_list_[0].assign(final_sol);
            if (this->env_->debug_level_)
                std::cout << "0: final cost = " << final_sol.get_Cost() << lf;
            for (int i = 1; i < np; ++i)
            {
                mpi::recv(i, comm) >> this->tmp_;
                pool.sol_list_[i].init(this->env_, this->rnd_);
                pool.sol_list_[i].assign(this->tmp_);
                if (this->env_->debug_level_)
                    std::cout << i << ": final cost = " << this->tmp_.get_Cost() << lf;
            }
        }
        else
        {
            mpi::send(0, comm) << final_sol;
        }
        comm.barrier();
    }

    void clear_MPI(int prev, mpi::communicator& comm)
    {
        comm.barrier();
        if (!coop_.is_Async_Mode())
            return;
        //std::cout << comm.rank() << ":enter clear_MPI(...)" << std::endl;
        mpi::recv in(prev, comm);
        while (in.is_Data_Available(0))
        {
            //std::cout << comm.rank() << ":***zombi-migrant killed" << std::endl;
            int stop_flag;
            in >> stop_flag;
            in >> this->tmp_;
        }
        comm.barrier();
        //std::cout << comm.rank() << ":leave clear_MPI(...)" << std::endl;
    }
};
//__________________________________________________________________________________
//__________________________________________________________________________________

//EOF!
